package com.xiang.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@Slf4j
//@WebFilter(urlPatterns = "/sys/common/sendSmsCode", filterName = "HqvtWrapperFilter", dispatcherTypes = DispatcherType.REQUEST)
public class HqvtWrapperFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    // Do nothing
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    ServletRequest requestWrapper;
    long start = System.currentTimeMillis();
    try {
      if (Objects.nonNull(request) && (request instanceof HttpServletRequest)
          && StringUtils.hasText(request.getContentType())
          && request.getContentType().toLowerCase().contains(MediaType.APPLICATION_JSON_VALUE)) {
        requestWrapper = new RequestWrapper((HttpServletRequest) request);
        chain.doFilter(requestWrapper, response);
      } else {
        chain.doFilter(request, response);
      }
    } catch (Exception e) {
        log.error("ex: ",e);
    }
    long end = System.currentTimeMillis();
    log.info("doFilter耗时：{} 毫秒" ,(end-start));
  }

  @Override
  public void destroy() {
    // Do nothing
  }
}
